<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="FreeRTOS提供了一个消息队列模块，通过消息队列，我们可以实现任务和任务间的数据传递；中断服务程序和任务间的数据传递。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-使用消息队列">
<meta property="og:url" content="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="FreeRTOS提供了一个消息队列模块，通过消息队列，我们可以实现任务和任务间的数据传递；中断服务程序和任务间的数据传递。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/queue_size.png">
<meta property="article:published_time" content="2022-12-11T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T14:01:48.075Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/queue_size.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/","path":"2022/12/12/FreeRTOS-use-queue/","title":"FreeRTOS-使用消息队列"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-使用消息队列 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-使用消息队列 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-使用消息队列
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-12 00:00:00" itemprop="dateCreated datePublished" datetime="2022-12-12T00:00:00+08:00">2022-12-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
FreeRTOS提供了一个消息队列模块，通过消息队列，我们可以实现任务和任务间的数据传递；中断服务程序和任务间的数据传递。
</center>
<span id="more"></span>

<hr>
<p>一些更详细的FreeRTOS消息队列内部实现细节，可以参考<a href="https://fengxun2017.github.io/2022/12/08/FreeRTOS-queue-internal-details/">FreeRTOS-消息队列内部细节</a></p>
<p>FreeRTOS提供的消息队列，是固定大小的消息队列（可以同时存放的最大消息数量，是在创建时就指定的），并且其中每个消息的大小也是固定的，如下图所示：<br><img src="/2022/12/12/FreeRTOS-use-queue/queue_size.png"></p>
<br>


<p>创建消息队列的API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">QueueHandle_t <span class="title function_">xQueueCreate</span><span class="params">( UBaseType_t uxQueueLength, UBaseType_t uxItemSize )</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p>uxQueueLength：消息队列大小</p>
</li>
<li><p>uxItemSize：消息队列中每个消息的大小。</p>
</li>
<li><p>返回值：消息队列句柄，用来唯一识别创建的这个消息队列。如果堆内存资源不够，则返回NULL。</p>
</li>
</ul>
<p>消息队列创建成功后，即可向该消息队列中发送消息，或从中提取消息。<br>发送消息的API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xQueueSend</span><span class="params">( QueueHandle_t xQueue, </span></span><br><span class="line"><span class="params">                        <span class="type">const</span> <span class="type">void</span> * pvItemToQueue, </span></span><br><span class="line"><span class="params">                        TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>xQueue：上述的创建消息队列API 返回的，用来标识一个消息队列的句柄。</p>
</li>
<li><p>pvItemToQueue：待发送的消息。</p>
</li>
<li><p>xTicksToWait：如果消息队列当前已经满了，那么本次发送数据就会导致调用该api的任务进入阻塞态，以等待消息队列有空闲位置可以放下本次要发送的数据。等待的时间即为<code>xTicksToWait</code>。如果为0，则表示不等待，立刻返回。注意，该值需要使用宏<code>pdMS_TO_TICKS(ms)</code>将时间转换成内核可以识别的tick数。</p>
</li>
<li><p>返回值：发送成功则返回<code>pdPASS</code>，否则即队列满了，无法发送。</p>
</li>
</ul>
<p>从消息队列中获取消息的API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xQueueReceive</span><span class="params">( QueueHandle_t xQueue, </span></span><br><span class="line"><span class="params">                            <span class="type">void</span> *pvBuffer, </span></span><br><span class="line"><span class="params">                            TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>xQueue：上述创建消息队列API 返回的，用来标识一个消息队列的句柄。</p>
</li>
<li><p>pvBuffer：接收消息使用的缓存。</p>
</li>
<li><p>xTicksToWait：如果消息队列当前是空的，那么本次提取数据就会导致调用该api的任务进入阻塞态，以等待消息队列有消息可以提取。等待的时间即为<code>xTicksToWait</code>。如果为0，则表示不等待，立刻返回。</p>
</li>
<li><p>返回值：提取消息成功则返回<code>pdPASS</code>，否则即队列为空，获取不到数据。</p>
</li>
</ul>
<br>

<p>示例代码：我们创建两个任务<code>sender1</code>和<code>sender2</code>分别向同一个消息队列中发送消息。创建一个<code>receiver</code>任务，消费消息队列中的消息。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> &#123;</span></span><br><span class="line">    <span class="type">int</span> cmd_id;</span><br><span class="line">    <span class="type">int</span> other;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">QueueHandle_t my_queue;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    bsp_init();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建消息队列</span></span><br><span class="line">    my_queue = xQueueCreate(<span class="number">5</span>, <span class="keyword">sizeof</span>(<span class="keyword">struct</span> MyData));</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != my_queue) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 创建发送/接收任务，并将创建的消息队列作为参数传递给任务</span></span><br><span class="line">        <span class="comment">// 任务内部，使用创建的消息队列</span></span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(sender1_task, <span class="string">&quot;sender1_task&quot;</span>, <span class="number">100</span>, my_queue, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">         &amp;&amp; pdPASS == xTaskCreate(sender2_task, <span class="string">&quot;sender2_task&quot;</span>, <span class="number">100</span>, my_queue, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">         &amp;&amp; pdPASS == xTaskCreate(receiver_task, <span class="string">&quot;receiver_task&quot;</span>, <span class="number">100</span>, my_queue, <span class="number">1</span>, <span class="literal">NULL</span>)) &#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;something wrong\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>发送任务中：通过参数获得消息队列</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">sender1_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueHandle_t my_queue = (QueueHandle_t)pvParameters;</span><br><span class="line">    </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    data.cmd_id = <span class="number">0</span>;</span><br><span class="line">    data.other = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 发送消息</span></span><br><span class="line">        xQueueSend(my_queue, &amp;data, <span class="number">0</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">sender2_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueHandle_t my_queue = (QueueHandle_t)pvParameters;</span><br><span class="line">    </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    data.cmd_id = <span class="number">1</span>;</span><br><span class="line">    data.other = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 发送消息</span></span><br><span class="line">        xQueueSend(my_queue, &amp;data, <span class="number">0</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>数据接收任务：通过参数获得消息队列</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">receiver_task</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    QueueHandle_t my_queue = (QueueHandle_t)pvParameters;</span><br><span class="line">   </span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xQueueReceive(my_queue, &amp;data, pdMS_TO_TICKS(<span class="number">1500</span>))) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;receive cmd:%d\n&quot;</span>, data.cmd_id);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序运行结果如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">...</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>通过上面的例子，我们可以发现几个FreeRTOS消息队列特性：</p>
<ul>
<li>每次发送的消息是固定大小的，即在创建消息队列时指定的uxItemSize。但是现实开发中，有些场景需要发送的数据是变长的。针对这种问题可以通过传递数据指针来解决，例如将消息队列中存放的消息定义成如下格式：<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> &#123;</span></span><br><span class="line">    <span class="type">int</span> data_len;</span><br><span class="line">    <span class="type">void</span> *pdata;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
消息接收方提取消息后，通过<code>pdata</code>获得实际数据存储位置，通过<code>data_len</code>获取实际数据长度。<br></li>
<li>FreeRTOS提供的消息队列，是多任务（多线程）安全的。示例代码中，存在多个发送&#x2F;接收任务对同一个消息队列进行操作，但我们并未对该消息队列（在这里是属于共享资源）的访问进行临界区保护。因为FreeRTOS的消息队列模块内部实现中，已经做了临界区保护。</li>
</ul>
<p>实际开发中，另一个常见的需求可能是，我们在收到某个中断事件后，需要向消息队列中发送一个消息。中断环境下，不能使用上文的发送API（上文的发送api可能会导致调用者阻塞，中断处理函数中是不允许阻塞的），需要使用FreeRTOS提供的带FromISR 后缀的发送API：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xQueueSendFromISR</span><span class="params">( QueueHandle_t xQueue, </span></span><br><span class="line"><span class="params">                                <span class="type">const</span> <span class="type">void</span> *pvItemToQueue, </span></span><br><span class="line"><span class="params">                                BaseType_t *pxHigherPriorityTaskWoken )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xQueue：标识一个消息队列的句柄。</li>
<li>pvItemToQueue：待发送的消息。</li>
<li>pxHigherPriorityTaskWoken：当我们在中断处理程序中向消息队列发送消息一个消息后，如果存在另一个任务刚好在等待消息队列有数据，那么该任务就会恢复就绪。如果该任务的优先级比当前任务（被中断服务程序打断的任务）更高，pxHigherPriorityTaskWoken就会被设置为True。表示有更高优先级的任务就绪了。</li>
</ul>
<p>例如，我们在前面的例子上，再一个按键中断处理函数中向消息队列发送消息的示例：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">GPIOTE_IRQHandler</span><span class="params">(<span class="type">void</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line">    <span class="keyword">if</span> ( NRF_GPIOTE-&gt;EVENTS_PORT == <span class="number">1</span> )&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//中断处理函数中要清除event,不然会导致一直产生中断</span></span><br><span class="line">        NRF_GPIOTE-&gt;EVENTS_PORT = <span class="number">0</span>;      </span><br><span class="line"></span><br><span class="line">        <span class="comment">// 判断按键，发送消息</span></span><br><span class="line">        <span class="keyword">if</span>(IS_BUTTON_PRESSED(BUTTON_1)) &#123;</span><br><span class="line">            <span class="class"><span class="keyword">struct</span> <span class="title">MyData</span> <span class="title">data</span>;</span></span><br><span class="line">            data.cmd_id = <span class="number">2</span>;</span><br><span class="line">            data.other = <span class="number">2</span>;</span><br><span class="line">            xQueueSendFromISR(my_queue, &amp;data, &amp;higher_task_woken);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果higher_task_woken=True，表示有更高优先级任务就绪了</span></span><br><span class="line">    <span class="comment">// 我们使用的是抢占式调度，只要有更高优先级的任务就绪，应该让其立刻运行。</span></span><br><span class="line">    <span class="comment">// 下面的代码就是，判断有更高优先级就绪时，就会设置任务切换中断。那么当前中断函数退出后，就会立刻触发任务切换，让最高优先级的就绪任务运行。</span></span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序运行结果如下所示，每次按键按下，都能收到 <code>cmd_id = 2</code> 的消息：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">receive cmd:2</span><br><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">receive cmd:2</span><br><span class="line">receive cmd:0</span><br><span class="line">receive cmd:1</span><br><span class="line">receive cmd:2</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972
<br>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/" title="FreeRTOS-使用消息队列">http://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/12/08/FreeRTOS-queue-internal-details/" rel="prev" title="FreeRTOS-消息队列内部细节">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-消息队列内部细节
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/12/14/FreeRTOS-use-queueset/" rel="next" title="FreeRTOS-使用消息队列集合">
                  FreeRTOS-使用消息队列集合 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
